//2009/08/27 13:32:44
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <queue>
#include <sstream>
#include <algorithm>

using namespace std;

int xx[] = {1, 0, -1, 0};
int yy[] = {0, -1, 0, 1};

class MountainWalk
{
public:
    int cellsVisited(vector <string> areaMap, int heightDifference)
    {
		return count(0, 0, areaMap, heightDifference);
    }
    bool inBound(int x, int y, vector<string>& map)
    {
        if (x>=0 && x<map.size() && y>=0 && y<map[0].size()) return true;
        return false;
    }
    int next2go(int x, int y, vector<string>& map, int h)
    {
        for (int i=0; i<4; i++)
        {
            int xtemp = x + xx[i];
            int ytemp = y + yy[i];
            if (inBound(xtemp, ytemp, map) && map[xtemp][ytemp] != -1 && abs(map[x][y] - map[xtemp][ytemp]) <= h) 
			{
				map[x][y] = -1;
				return i;
			}
        }
		return -1;
    }
	int count(int x, int y, vector<string>& map, int h)
	{
		int idx = next2go(x, y, map, h);
		if(idx == -1) return 1;
		return 1 + count(x+xx[idx], y+yy[idx], map, h);
	}
};
